﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MiniErp.Core.Filters
{
    /// <summary>
    /// API回传值拦截器      
    /// </summary>
    public class ResultFilter : IActionFilter
    {
        /// <summary>
        /// 方法运行前发生
        /// </summary>
        public void OnActionExecuting(ActionExecutingContext context)
        {

        }
        /// <summary>
        /// 方法运行后发生
        /// </summary>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //成功时回传值
            var successResult = new JsonResult(
                       context.Result is ObjectResult result ? new
                       {
                           Status = true,
                           Code = 200,
                           Message = "请求成功",
                           Data = result.Value
                       } : new
                       {
                           Status = true,
                           Code = 200,
                           Message = "请求成功"
                       }
                   );

            //获取当前HTTP请求类型
            context.Result = context.ActionDescriptor.EndpointMetadata.FirstOrDefault(attr => attr is HttpMethodAttribute) switch
            {
                HttpDeleteAttribute => new JsonResult(new { Status = true, Code = 200, Message = "请求成功" }),
                HttpPostAttribute => successResult,
                HttpGetAttribute => successResult,
                HttpPutAttribute => successResult,
                _ => successResult
            };

            ((JsonResult)context.Result).StatusCode = 200;
        }
    }


}
